﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.UI;
using System.IO;
using cludg.Web.Core.Utils;
using global::Recaptcha;

namespace cludg.Web.Core.Captcha
{
	using Controllers;

	public static class CaptchaHelper
	{
		public static string GenerateCaptcha(this HtmlHelper html)
		{
			var controller = html.ViewContext.Controller as BaseController;
			if (controller == null)
			{
				throw new ApplicationException("GenerateCaptcha helper can be user only with BaseController objects.");
			}

			var captchaControl = new RecaptchaControl
			{
				ID = "recaptcha",
				Theme = "white",
				PublicKey = controller.Settings["ReCAPTHA_PublicKey"].ToString(),
				PrivateKey = controller.Settings["ReCAPTHA_PrivateKey"].ToString()
			};
			var htmlWriter = new HtmlTextWriter(new StringWriter());
			captchaControl.RenderControl(htmlWriter);
			return htmlWriter.InnerWriter.ToString();
		}

		public static MvcHtmlString AddCaptchaFields(this HtmlHelper html, string label)
		{
			var controller = html.ViewContext.Controller as BaseController;
			if (controller == null)
			{
				throw new ApplicationException("AddCaptchaFields helper can be user only with BaseController objects.");
			}

			var result = new StringBuilder();
			if (CaptchaUtil.NeedUseCaptcha(controller))
			{
				result.Append("<div>");
				result.AppendFormat("<label for=\"recaptcha_response_field\">{0}</label>", label);
				result.Append(html.GenerateCaptcha());
				result.Append(html.ValidationMessage("Captcha"));
				result.Append("</div>");
			}
			return MvcHtmlString.Create(result.ToString());
		}
	}
}
